# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" MindVideo Classification infer script. """

import os
from mindspore.ops.operations.array_ops import Argmax
import numpy as np

import mindspore
import mindspore.dataset as ds
from mindspore import context, load_checkpoint, load_param_into_net
from mindspore.context import ParallelMode
from mindspore.train import Model
from mindspore.communication.management import init, get_rank, get_group_size
from mindspore.ops import operations as P

from mindvideo.common.check_param import Validator, Rel
from mindvideo.common.utils.config import parse_args, Config
from mindvideo.datasets.dataloader import build_dataloader 
from mindvideo.models import build_classifier


def main(pargs):
    config = Config(pargs.config)

    # set config context
    context.set_context(**config.context)

    # run distribute
    if config.infer.run_distribute:
        if config.device_target == "Ascend":
            init()
        else:
            init("nccl")
        context.set_auto_parallel_context(device_num=get_group_size(),
                                          parallel_mode=ParallelMode.DATA_PARALLEL,
                                          gradients_mean=True)

    data_loader = build_dataloader(config.data_loader)
    dataset_infer = data_loader()
    Validator.check_int(dataset_infer.get_dataset_size(), 0, Rel.GT)
    dataloader_infer = ds.GeneratorDataset(dataset_infer, 
                                           ["data", "label"],
                                           shuffle=False)

    # set network
    network = build_classifier(config.model)

    # load pretrain model
    param_dict = load_checkpoint(config.infer.pretrained_model)
    load_param_into_net(network, param_dict)

    # init the whole Model
    model = Model(network)

    # begin to infer
    print(f'[Start infer `{config.model_name}`]')
    print("=" * 80)
    argmax_op = P.Argmax()
    for data in dataloader_infer.create_dict_iterator():
        outputs = model.predict(data["data"])
        outputs = argmax_op(outputs)
        print("Predict:", outputs)
        print("Label:", data["label"])
    print(f'End of infer {config.model_name}.')


if __name__ == '__main__':
    args = parse_args()
    main(args)
